<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table v-loading="loading" :data="tableData">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="submit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="setRole(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
            </template>
          </template>

        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <el-pagination
          :current-page="pageParams.page"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="pageParams.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 放置分页组件 -->
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" :before-close="close">
        <!-- 表单内容 -->
        <el-form ref="form" label-width="120px" :model="form" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch v-model="form.state" size="mini" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="addRole">确定</el-button>
                <el-button size="mini" @click="close">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 放置权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="tree"
          node-key="id"
          :default-checked-keys="permIds"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import { getRoleList, addRoleList, updateRole, delRole, getRoleDetail, assignPrem } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  data () {
    return {
      permissionData: [],
      showPermissionDialog: false,
      permIds: [],
      id: null,
      loading: false,
      pageParams: {
        page: 1,
        pagesize: 5
      },
      tableData: [],
      total: null,
      showDialog: false,
      form: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    this.initTable()
  },
  methods: {
    // 封装
    async  initTable () {
      this.loading = true
      const data = await getRoleList(this.pageParams)

      this.tableData = [...data.rows]
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.total = data.total
      this.loading = false
    },
    setRole (row) {
      row.isEdit = true
    },
    handleSizeChange (val) {
      this.pageParams.pagesize = val
      this.initTable()
    },
    handleCurrentChange (val) {
      this.pageParams.page = val
      this.initTable()
    },
    // 添加
    async addRole () {
      try {
        await this.$refs.form.validate()

        await addRoleList(this.form)
        this.$message.success('添加成功')

        this.close()
        this.initTable()
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑
    async   submit (row) {
      console.log(row)
      await updateRole({ ...row.editRow, id: row.id })

      this.initTable()
    },
    // 删除
    async  delRole (id) {
      await delRole(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1) this.pageParams.page--
      this.initTable()
    },
    close () {
      this.$refs.form.resetFields()
      this.showDialog = false
    },

    async btnPermission (id) {
      this.id = id
      const data = await getPermissionList()
      const res = transListToTreeData(data, 0)
      this.permissionData = res
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async  btnPermissionOK () {
      const res = this.$refs.tree.getCheckedKeys()

      await assignPrem({ id: this.id, permIds: res })

      this.$message.success('分配权限成功')

      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
